express = require 'express'
mysqlStore = require('connect-mysql') express
lessMiddleware = require 'less-middleware'
coffeeMiddleware = require 'connect-coffee-script'
path = require 'path'
fs = require 'fs'
log = require('./utils/log').getLogger 'master'
enums = require './utils/enums'

app = express()

models = require './models'

sessionOptions = 
	pool : true
	config : require('./config').connection.production

configRoutes = (app)->
	fs.readdirSync(path.join __dirname, 'routes').forEach (file)->
		for key, value of require "./routes/#{file}" when ['get','del','post','put', 'all'].indexOf(key.split(' ')[0])>=0
			app[key.split(' ')[0]] key.split(' ')[1], value
app.configure ()->
	app.locals = 
		enums : enums

	app.set 'jade', require('jade').__express
	app.set 'view engine', 'jade'
	app.set 'views', path.resolve __dirname, './views'

	app.use '/static/coffee', coffeeMiddleware
		src: '../web/coffee'
		bare: true
	app.use '/static/less', lessMiddleware path.resolve(__dirname, '../web/less').toString()
	app.use '/static', express.static path.resolve __dirname,'../web' 

	app.use express.bodyParser()
	app.use express.cookieParser()

	app.use express.session
		secret: 'qingkr'
		store : new mysqlStore sessionOptions
		cookie : 
			maxAge :1000*60*60*24*7
	app.use (req, res, next)->
		req.locals = app.locals
		req.callback = (err, result)->
			if err
				log.logError err
				return res.send(400 , err) 
			res.send 200
		req.checkAuth = (role)->
			return req.session.user?.role is role
			if role is 'admin'
				res.redirect '/admin/login'
			if role is 'user'
				res.redirect '/user/login'
		req.models = models
		next null
	configRoutes app
	return app

if require.main is module
	app.listen process.argv[2], ()->
		console.log "server start on #{process.argv[2]}"
		process.on 'uncaughtException', (err)->
			log.logError err








